package org.example.thread.testCompletableFuture;

import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * @author liyishan
 * @date 2024/3/5 16:13
 * @apiNote
 */

public class MonitoringThreadPoolExecutor extends ThreadPoolExecutor {
    public MonitoringThreadPoolExecutor(int  corePoolSize, int maximumPoolSize, long keepAliveTime, TimeUnit unit, BlockingQueue<Runnable> workQueue){
        super(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue);
    }

    @Override
    protected void beforeExecute(Thread t, Runnable r) {
        super.beforeExecute(t, r);
        // 在任务执行之前的操作，例如记录任务的开始时间
        long startTime = System.currentTimeMillis();
        // 将任务开始时间存储在ThreadLocal中，以便在afterExecute方法中获取
        ThreadLocalMonitor.startTime.set(startTime);
    }

    @Override
    protected void afterExecute(Runnable r, Throwable t) {
        super.afterExecute(r, t);
        // 在任务执行之后的操作，例如记录任务的执行时间、统计任务的执行情况等
        long endTime = System.currentTimeMillis();
        long executionTime = endTime - ThreadLocalMonitor.startTime.get();
        // 打印任务的执行时间
        System.out.println("Task execution time: " + executionTime + "ms");
    }

}
